angular.module('qiniuUpload', [])
    .factory('qiniuUpload', [
        '$cordovaFileTransfer', 'httpService', 'ENV', '$q', 'loading', 'camera',
        function($cordovaFileTransfer, httpService, ENV, $q, loading, camera) {
            var q = '',
                upload;
            upload = function(fileURL) {
                q = $q.defer();
                httpService.query('upload/uploadToken').then(function(res) {
                    var fail, ft, key, options, params, random_int, win, date;
                    if (res.code === 200) {
                        win = function(r) {
                            q.resolve(res.data.qndomain + JSON.parse(r.response).key);
                        };
                        fail = function(error) {
                            q.reject(JSON.stringify(error));
                        };
                        options = new FileUploadOptions();
                        options.fileKey = 'file';

                        options.fileName = fileURL.substr(fileURL.lastIndexOf('/') + 1);
                        date = function() {
                            var date_str;
                            date_str = '';
                            date = new Date();
                            date_str += date.getFullYear();
                            date_str += date.getMonth() + 1;
                            date_str += date.getDate();
                            date_str += date.getHours();
                            date_str += date.getMinutes();
                            date_str += date.getSeconds();
                            return date_str;
                        };
                        random_int = parseInt(Math.random() * 1000000);
                        key = 'usr_app_' + ENV.appId + '_msgimg_' + date() + random_int;
                        params = {
                            key: key,
                            token: res.data.upToken,
                            x: {
                                variable: random_int
                            }
                        };
                        options.params = params;
                        ft = new FileTransfer();
                        ft.upload(fileURL, 'http://upload.qiniu.com/', win, fail, options);
                    } else {
                        loading.prompt('网络异常!');
                    }
                });
                return q.promise;
            };
            return {
                upload: upload
            };
        }
    ]);
